//
//  ShoppingMallController.m
//  ELife
//
//  Created by feng lu on 11-6-14.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ShoppingMallController.h"
#import "GTMBase64.h"
#include "GDataXMLNode.h"
#import "ShoppingMallDetails.h"
#import "TuangouController.h"


@implementation ShoppingMallController
@synthesize tuangou;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [myMutabDic release];
    [myImageArray release];
    [myList release];
    [hotworkArray release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    app = [ELifeAppDelegate App];
    myImageArray = [[NSMutableArray alloc] initWithCapacity:10];
    myMutabDic = [[NSMutableArray alloc] initWithCapacity:10];
    flowcover = [[FlowCoverView alloc] initWithFrame:CGRectMake(0, 90, 320, 100)];
    [flowcover setDelegate:self];
    
    [self.view addSubview:flowcover];
    NSLog(@"%@", [app tuangou]);
    if ([[app tuangou] count] > 0) {
        [tuangou setTitle:[[app tuangou] objectAtIndex:0] forState:UIControlStateNormal];
    }
    
    NSString* urlPath = [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", urlPath, @"init_mall_info.php"]];
    //    
        NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iMallInfoRequest:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
        [[app httpRequestPoint] openUrl:dic target:self];
    //[flowcover ]
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
//    [app controllNum:0 setNavigationBar:NO animated:NO];
}


-(void) openUrl
{
    
    for (NSDictionary* dic in myMutabDic) {
        NSURL* url = [NSURL URLWithString:[dic objectForKey:@"recommand_image"]];
        //    
        NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iFinishImage:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
        [[app httpRequestPoint] openUrl:dic target:self];
        
        [NSThread sleepForTimeInterval:1];
    }
    

}

#pragma mark 搜索回调
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
	return YES;
}// return NO to not become first responder
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
}// called when text starts editing
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    
}// return NO to not resign first responder
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}// called when text ends editing


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	
    
}// called when text changes (including clear)



- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger index = [indexPath row];
	
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	NSLog(@"%@", searchBar.text);
    
    
    [app startLoginView];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"search_goods" forKey:@"action"];
    [param setObject:[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"keywords"];
    [param setObject:@"1" forKey:@"page"];
    [param setObject:@"10" forKey:@"limit"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"goods.php?"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
    
    [searchBar resignFirstResponder];
	
	[self.searchDisplayController setActive:NO];
    
}


#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)request
{ 
    [app finishLoginView];
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:request] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:request] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
//    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    //NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
//    NSLog(@"--------body:--------\n%@", bodyElement);
    GDataXMLElement* goods = [[bodyElement elementsForName:@"goods"] objectAtIndex:0];
    GDataXMLElement* item = [goods elementsForName:@"item"];
    
    NSMutableArray* myArray = [NSMutableArray arrayWithCapacity:100];
    for (int i = 0; i<[item count]; i++) {
        NSLog(@"%@",[item objectAtIndex:i]);
        NSString* name = [[[[item objectAtIndex:i] elementsForName:@"goods_name"] objectAtIndex:0] stringValue];
        NSLog(@"%@", name);
        NSString* id = [[[[item objectAtIndex:i] elementsForName:@"goods_id"] objectAtIndex:0] stringValue];
        NSString* price = [[[[item objectAtIndex:i] elementsForName:@"goods_price"] objectAtIndex:0] stringValue];
        NSString* vip = [[[[item objectAtIndex:i] elementsForName:@"goods_vip"] objectAtIndex:0] stringValue];
        NSString* number = [[[[item objectAtIndex:i] elementsForName:@"goods_number"] objectAtIndex:0] stringValue];
        NSString* pic = [[[[item objectAtIndex:i] elementsForName:@"goods_pic"] objectAtIndex:0] stringValue];
        
        [myArray addObject:[NSArray arrayWithObjects:id, name, price, vip, number, pic, nil]];
    }
    
    if (myList == nil) {
        myList = [[ShoppingMailList alloc] initWithStyle:UITableViewStyleGrouped];
    }
    
    [myList setListData:myArray];
    
//    [self.view addSubview:myList.view];
    [self.navigationController pushViewController:myList animated:YES];
    
}

-(void)iMallInfoRequest:(NSData*) data
{
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:data] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    //    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    GDataXMLElement* goods = [[bodyElement elementsForName:@"businessinfo"] objectAtIndex:1];
    GDataXMLElement* recommandations = [[goods elementsForName:@"recommandations"] objectAtIndex:0];
    GDataXMLElement* recommand = [recommandations elementsForName:@"recommand"];
    
//    NSLog(@"--------goods:--------\n%@", recommand);
    [myMutabDic removeAllObjects];

    for (int i = 0; i<[recommand count]; i++) {
        NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithCapacity:3];
        GDataXMLElement* recommand2 = [recommand objectAtIndex:i];
        NSString* recommand_id = [[[recommand2 elementsForName:@"recommand_id"] objectAtIndex:0] stringValue];
        NSString* recommand_name = [[[recommand2 elementsForName:@"recommand_name"] objectAtIndex:0] stringValue];
        NSString* recommand_image = [[[recommand2 elementsForName:@"recommand_image"] objectAtIndex:0] stringValue];
        
//        NSLog(@"%@", recommand_image);
        
        [dic setObject:recommand_id forKey:@"recommand_id"];
        [dic setObject:recommand_name forKey:@"recommand_name"];
        [dic setObject:recommand_image forKey:@"recommand_image"];
        
        [myMutabDic addObject:dic];
    }
    UILabel* label = [self.view viewWithTag:6001];
    [label setText:[[myMutabDic objectAtIndex:0] objectForKey:@"recommand_name"]];
    
//    NSLog(@"%@", myMutabDic);
    [self openUrl];
    goods = [[bodyElement elementsForName:@"businessinfo"] objectAtIndex:0];
    NSLog(@"--------goods:--------\n%@", goods);
    GDataXMLElement* producttypes = [goods elementsForName:@"producttypes"];
    
    GDataXMLElement* producttype = [[producttypes objectAtIndex:0] elementsForName:@"producttype"];
    NSLog(@"--------recommandations:--------\n%@", producttype);
    if (hotworkArray == nil) {
        hotworkArray = [[NSMutableArray alloc] initWithCapacity:20];
    }else
        [hotworkArray removeAllObjects];

    
    for (int j = 0; j < [producttype count]; j++) {
        
        NSString* nameStr = [[[[producttype objectAtIndex:j] elementsForName:@"type_name"] objectAtIndex:0] stringValue];
        NSString* productStr = [[[[producttype objectAtIndex:j] elementsForName:@"product_type"] objectAtIndex:0] stringValue];
        [hotworkArray addObject:[NSArray arrayWithObjects:nameStr, productStr, nil]];
    }
    NSLog(@"%@", hotworkArray);
    [self showHotWork];
    
}


-(void) showHotWork
{
    int index = 4041;
    for (int i = 0; i<[hotworkArray count]; i++) {
        if (i > 5) {
            break;
        }
        UIButton* button = (UIButton*)[self.view viewWithTag:index];
        [button setTitle:[[hotworkArray objectAtIndex:i] objectAtIndex:0] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(openHotWork:) forControlEvents:UIControlEventTouchUpInside];
        index++;
    }
}

-(void) openHotWork:(id)sender
{
    UIButton* button = (UIButton*)sender;
    NSInteger index = button.tag-4041;
    NSString* catalog_id = [[hotworkArray objectAtIndex:index] objectAtIndex:1];
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"catalog_goods" forKey:@"action"];
    [param setObject:catalog_id forKey:@"catalog_id"];
    [param setObject:@"order_by_price" forKey:@"order"];
    [param setObject:@"1" forKey:@"page"];
    [param setObject:@"20" forKey:@"limit"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"goods.php?"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"catalog_goods:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];

}

-(void)catalog_goods:(NSData*) data
{
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];

}


-(IBAction) TuangouAction
{
    TuangouController* tuangou = [TuangouController alloc];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:tuangou];
    [self presentModalViewController:navigationController animated:YES];
    [navigationController release];

    [tuangou release];
}




-(void)iFinishImage:(NSData*) data
{
    UIImage* image = [UIImage imageWithData:data];
    [myImageArray addObject:image];
    if ([myImageArray count] == [myMutabDic count]) {
        [flowcover draw];
    }
    
}


- (void)iRequestFailed
{
    [app finishLoginView];
}


#pragma mark -
#pragma mark flowCover
- (int)flowCoverNumberImages:(FlowCoverView *)view
{
    return [myMutabDic count];
}


- (UIImage *)flowCover:(FlowCoverView *)view cover:(int)cover
{
//    if (cover == 0) {
//       return [UIImage imageNamed:@"90x90-10.jpg"];
//    }else if (cover == 1) {
//       return [UIImage imageNamed:@"90x90-11.jpg"];
//    }else if (cover == 2) {
//       return [UIImage imageNamed:@"90x90-12.jpg"];
//    }
    
    [myImageArray objectAtIndex:cover];
}


- (void)flowCover:(FlowCoverView *)view didSelect:(int)cover
{
     NSLog(@"select=%i", cover);
    if ([myMutabDic count] > 0) {
        NSLog(@"%@", myMutabDic);
        ShoppingMallDetails* details = [[ShoppingMallDetails alloc] initWithStyle:UITableViewStyleGrouped];
        [details setGood_id:[[myMutabDic objectAtIndex:cover]objectForKey:@"recommand_id"]];
        [self.navigationController pushViewController:details animated:YES];
        [details release];

    }
       
}


- (void)flowCover:(FlowCoverView *)view dangqian:(int)cover
{
    NSLog(@"dangqian=%i", cover);
    
    UILabel* label = [self.view viewWithTag:6001];
    [label setText:[[myMutabDic objectAtIndex:cover] objectForKey:@"recommand_name"]];
    
}

@end
